﻿@page "/users/{id}/{action}"
@layout SimpleIdServer.IdServer.Website.Shared.MainLayout
@attribute [Authorize("Authenticated")]
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.RealmStore;
@using SimpleIdServer.IdServer.Website.Stores.UserStore;
@inherits Fluxor.Blazor.Web.Components.FluxorLayout
@inject NotificationService notificationService
@inject NavigationManager navigationManager
@inject IState<UserState> userState
@inject IUrlHelper urlHelper
@inject IDispatcher dispatcher

<SidAuthorizeView Roles=@($"/users/manage,/users/view")>
    <Authorized>
        <RadzenBreadCrumb>
            <RadzenBreadCrumbItem Path="@urlHelper.GetUrl("/users")" Text="@Global.Users" />
            <RadzenBreadCrumbItem Text="@Global.UserDetails" />
        </RadzenBreadCrumb>

        <RadzenText class="mt-3 mb-3 no-margin" Text="@userState.Value.User?.Name" TextStyle="TextStyle.DisplayH3" />

        <RadzenStack Orientation="Orientation.Horizontal" class="mb-3">
            @if (!string.IsNullOrWhiteSpace(userState.Value.User?.Source))
            {
                <RadzenBadge Text="@userState.Value.User?.Source" IsPill="true" BadgeStyle="BadgeStyle.Info"></RadzenBadge>
            }
            @if (userState.Value.User != null)
            {
                <RadzenStack Orientation="Orientation.Horizontal">
                    <RadzenSwitch Value=@(userState.Value.User.Status == UserStatus.ACTIVATED) ValueChanged="ToggleUser" />
                    <RadzenBadge BadgeStyle=@(userState.Value.User.Status == UserStatus.ACTIVATED ? BadgeStyle.Success : BadgeStyle.Danger) Text=@(userState.Value.User.Status == UserStatus.ACTIVATED ? Global.Active : Global.Blocked)></RadzenBadge>
                    @if(userState.Value.User.ActivePassword != null)
                    {
                        <RadzenSwitch Value=@(userState.Value.User.ActivePassword.IsTemporary) ValueChanged="ToggleTemporaryPassword" />
                        <RadzenBadge BadgeStyle=@(userState.Value.User.ActivePassword.IsTemporary ? BadgeStyle.Danger : BadgeStyle.Success) Text=@(userState.Value.User.ActivePassword.IsTemporary ? Global.IsTemporaryPwd : Global.IsNotTemporaryPwd)></RadzenBadge>
                    }
                </RadzenStack>
            }
        </RadzenStack>        

        <RadzenCardLoader Variant="Variant.Filled" IsLoading=@userState.Value.IsLoading>
            <RadzenTabs Change=@OnChange @bind-SelectedIndex="selectedIndex">
                <Tabs>
                    <RadzenTabsItem Text="@Global.Details">
                        <UserSettings User="@userState.Value.User"></UserSettings>
                    </RadzenTabsItem>
                    <RadzenTabsItem Text="@Global.Consents">
                        <UserConsents User="@userState.Value.User"></UserConsents>
                    </RadzenTabsItem>
                    <RadzenTabsItem Text="@Global.Credentials">
                        <UserCredentials User="@userState.Value.User"></UserCredentials>
                    </RadzenTabsItem>
                    <RadzenTabsItem Text="@Global.Groups">
                        <UserGroups User="@userState.Value.User"></UserGroups>
                    </RadzenTabsItem>
                    <RadzenTabsItem Text="@Global.Claims">
                        <UserClaims UserId="@userState.Value.User?.Id"></UserClaims>
                    </RadzenTabsItem>
                    <RadzenTabsItem Text="@Global.Sessions">
                        <UserSessions User="@userState.Value.User"></UserSessions>
                    </RadzenTabsItem>
                    <RadzenTabsItem Text="@Global.ExternalIdProviders">
                        <UserProfiles User="@userState.Value.User"></UserProfiles>
                    </RadzenTabsItem>
                </Tabs>
            </RadzenTabs>
        </RadzenCardLoader>
    </Authorized>
    <NotAuthorized>
        @Global.NotAuthorized
    </NotAuthorized>
</SidAuthorizeView>

@code {
    Dictionary<string, int> mappingActionNameToIndex = new Dictionary<string, int>
    {
        { "settings", 0 },
        { "consents", 1 },
        { "credentials", 2 },
        { "groups", 3 },
        { "claims", 4 },
        { "sessions", 5 },
        { "profiles", 6 }
    };
    [Parameter]
    public string id { get; set; } = null!;

    [Parameter]
    public string? action { get; set; } = null;

    public bool IsActive
    {
        get; set;
    }

    int selectedIndex = 0;

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if(firstRender)
        {
            SubscribeToAction<GetUserFailureAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = act.ErrorMessage });
                StateHasChanged();
            });
            SubscribeToAction<UnblockUserSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.UserUnblocked });
            });
            SubscribeToAction<BlockUserSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = string.Format(Global.UserBlocked, act.UnblockDateTime) });
            });
            SubscribeToAction<GetUserSuccessAction>((act) =>
            {
                Init();
            });
            SubscribeToAction<DisableTemporaryPasswordSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.PasswordIsNotTemporary });
            });
            SubscribeToAction<EnableTemporaryPasswordAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.PasswordIsTemporary });
            });
            Init();
        }
    }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        if (string.IsNullOrWhiteSpace(id)) return;
        if (!string.IsNullOrWhiteSpace(action) && mappingActionNameToIndex.ContainsKey(action))
            selectedIndex = mappingActionNameToIndex[action];
        dispatcher.Dispatch(new GetUserAction { UserId = id });
    }

    private void OnChange(int index)
    {
        var rec = mappingActionNameToIndex.Single(kvp => kvp.Value == index);
        navigationManager.NavigateTo(urlHelper.GetUrl($"/users/{id}/{rec.Key}"));
    }

    private void ToggleUser(bool value)
    {
        IsActive = value;
        object act = value ? new UnblockUserAction { UserId = id } : new BlockUserAction { UserId = id };
        dispatcher.Dispatch(act);
    }

    private void ToggleTemporaryPassword(bool value)
    {
        IsActive = value;
        object act = value ? new EnableTemporaryPasswordAction { UserId = id } : new DisableTemporaryPasswordAction { UserId = id };
        dispatcher.Dispatch(act);
    }

    private void Init()
    {
        if (userState.Value.User == null)
        {
            return;
        }

        IsActive = userState.Value.User?.Status == UserStatus.ACTIVATED;
    }
}